<template>
  <div v-loading="loading" class="parentStyle">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row :gutter="20">
        <el-col :span="!otherBtnHide ? 16 : 24" class="dataForm" :style="{ padding: (!otherBtnHide ? '0 10px 0 10px' : '0 30px 0 10px') }">
          <div class="area-header">
            <span class="area-header-title">{{ $t('公示公告') }}</span>
          </div>
          <el-col :span="24">
            <el-form-item :label="$t('公告标题')" prop="title">
              <el-input v-model="form.title" :placeholder="$t('公告标题')" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item :label="$t('公告内容')" prop="context">
              <EditorTxt v-if="!loading" ref="editorText" v-model="form.context" :plugins="[]" :toolbar="[]" :height="400" :placeholder="$t('公告内容')" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="$t('是否发送邮件')" prop="sendEmailStatus">
              <el-radio-group v-model="form.sendEmailStatus" disabled>
                <el-radio :label="'true'"><span style="color: #82c023">{{ $t('发送') }}</span></el-radio>
                <el-radio :label="'false'"><span style="color: red;">{{ $t('不发送') }}</span></el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-col>
        <el-col :span="!otherBtnHide ? 8 : 24">
          <div class="area-header">
            <span class="area-header-title">{{ $t('随函附件') }}</span>
          </div>
          <div v-loading="uploadLoading">
            <el-table :element-loading-text="$t('上传中...')" :data.sync="form.fileList" border class="nowrapTable formTable printArea" style="max-height: 260px;">
              <el-table-column :label="$t('附件名称')" align="left" prop="name" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-link type="primary" @click="onlinePreview(scope.row.id)">{{ scope.row.name }}</el-link>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
        <el-col>
          <div class="area-header" style="margin-top: 40px;">
            <span class="area-header-title">{{ $t('出资人') }}</span>
          </div>
          <el-table v-loading="LpBulletinInvestorLoading" :data.sync="form.lpBaseList" border class="nowrapTable formTable printArea">
            <el-table-column :label="$t('出资人名称')" align="center" prop="userName" :show-overflow-tooltip="true" />
            <!--
            <el-table-column :label="this.$t('内容简述')" align="center" prop="title">
              <template slot-scope="scope">
                <span style="cursor: context-menu;width: 150px !important;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;display: inline-block;">
                  {{ scope.row.title }}
                </span>
              </template>
            </el-table-column>
            -->
            <el-table-column :label="$t('主送邮箱')" align="center" prop="lpEmail" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <div :style="{ 'white-space': isEmpty(scope.row.lpEmail) ? 'unset' : 'pre-wrap' }">
                  <el-tag
                    v-for="tag in splitEmail(scope.row, 'lpEmail')"
                    :key="tag + scope.$index"
                    :closable="!otherBtnHide"
                    size="mini"
                    style="margin: 0 2px 0 2px;"
                    :disable-transitions="false"
                    @close="handleClose(scope.row, scope.$index, tag, 'to')"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-select
                    v-if="lpEmailVisible[scope.row.lpId]"
                    v-model="scope.row.emailValue"
                    filterable
                    clearable
                    class="search-input"
                    size="mini"
                    @focus="querySearch(scope.row.emailValue, scope.$index, 'lpEmail', scope.row.lpId)"
                    @keyup.enter.native="handleEmailConfirm(scope.row, $event)"
                    @blur="handleEmailConfirm(scope.row, $event)"
                  >
                    <el-option
                      v-for="(item, index) in fileFormatArr[scope.row.lpId]"
                      :key="index"
                      :value="item.value"
                      :label="item.email"
                    />
                  </el-select>
                  <div v-else>
                    <el-button v-if="!otherBtnHide" style="height: 20px;" size="mini" @click="showEmailInput(scope.row)">
                      <i class="el-icon-plus" style="margin-top: -5px;position: absolute;margin-left: -5px;" />
                    </el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :label="$t('抄送邮箱')" align="center" prop="lpEmailCc" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <div :style="{ 'white-space': isEmpty(scope.row.lpEmailCc) ? 'unset' : 'pre-wrap' }">
                  <el-tag
                    v-for="tag in splitEmail(scope.row, 'lpEmailCc')"
                    :key="tag + scope.$index"
                    :closable="!otherBtnHide"
                    size="mini"
                    style="margin: 0 2px 0 2px;"
                    :disable-transitions="false"
                    @close="handleClose(scope.row, scope.$index, tag, 'cc')"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-select
                    v-if="lpEmailCcVisible[scope.row.lpId]"
                    v-model="scope.row.emailCcValue"
                    filterable
                    clearable
                    class="search-input"
                    size="mini"
                    @focus="querySearch(scope.row.emailCcValue, scope.$index, 'lpCcEmail', scope.row.lpId)"
                    @keyup.enter.native="handleEmailCcConfirm(scope.row, $event)"
                    @blur="handleEmailCcConfirm(scope.row, $event)"
                  >
                    <el-option
                      v-for="(item, index) in fileFormatArr[scope.row.lpId]"
                      :key="index"
                      :value="item.value"
                      :label="item.email"
                    />
                  </el-select>
                  <div v-else>
                    <el-button v-if="!otherBtnHide" style="height: 20px;" size="mini" @click="showEmailCcInput(scope.row)">
                      <i class="el-icon-plus" style="margin-top: -5px;position: absolute;margin-left: -5px;" />
                    </el-button>
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column v-if="form.tempLateBusinessType === 'callMoney'" :label="$t('认缴金额') + $t('金额单位')" align="center" prop="subscribedAmount" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.subscribedAmount, 'w' ) }}
              </template>
            </el-table-column>
            <el-table-column v-if="form.tempLateBusinessType === 'callMoney'" :label="$t('Call款金额') + $t('金额单位')" align="center" prop="callMoney" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                {{ moneyFormat(scope.row.callMoney, 'w') }}
              </template>
            </el-table-column>
            <el-table-column v-if="!otherBtnHide" :label="$t('发送状态')" align="center" prop="status" :show-overflow-tooltip="true">
              <template slot-scope="scope">
                <span v-if="scope.row.callMoney === 0 || scope.row.callMoney === '0'">
                  {{ $t('免发送') }}
                </span>
                <span v-else-if="scope.row.status === '发送成功' || scope.row.status === '发送失败'" :style="{color: scope.row.status === '发送失败' ? 'red' : '#48bd4a'}">
                  {{ $t(scope.row.status) }}
                  <el-tooltip v-show="scope.row.status === '发送失败'" :content="$t('发送lp邮箱失败. 疑似邮箱未填写或存在不正确的邮箱,请检查用户邮箱')" placement="top">
                    <i class="el-icon-question" />
                  </el-tooltip>
                  <el-tooltip v-show="scope.row.status === '发送成功'" :content="$t('发送成功')" placement="top">
                    <i class="el-icon-circle-check" />
                  </el-tooltip>
                </span>
                <span v-else>
                  {{ $t('待发送') }}
                </span>
              </template>
            </el-table-column>
            <el-table-column :label="$t('操作')" align="center" :min-width="145">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="text"
                  icon="el-icon-view"
                  @click="emailReviewView(scope.row)"
                >{{ $t('查看') }}</el-button>
                <el-button
                  v-if="(scope.row.status === '发送成功' || scope.row.status === '发送失败') && !otherBtnHide"
                  type="text"
                  size="mini"
                  class="el-icon-set-up"
                  @click="submitEmail(scope.row)"
                >{{ $t('重新发送') }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: center;">
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button v-if="form.status !== '已发送' && showBtnStatus" type="warning" @click="turnDown()">{{ $t("驳回") }}</el-button>
      <el-button v-if="form.status !== '已发送' && showBtnStatus" type="primary" @click="submitForm">{{ $t("发送") }}</el-button>
    </div>
    <!-- 预览 -->
    <OnlinePreview ref="OnlinePreview" />

    <!-- 查看内容详情 -->
    <el-dialog :title="title" :visible.sync="emailReviewViewOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <emailReviewView ref="emailReviewView" />
    </el-dialog>

  </div>
</template>

<script>
import EditorTxt from '@/components/Tinymce'
import emailReviewView from '@/views/fund/lpBase/lp/emailReviewView.vue'
import {
  getLpPublicBulletin,
  updateReviewStatus,
  resendReviewAnnouncement
} from '@/api/fund/lpBase/lp/affiche/affiche.js'
import { listLpAnnouncementTemplate } from '@/api/fund/lpBase/lp/affiche/afficheListTemplate'
import { listDealContacts } from '@/api/deal/contact/contactsPerson'
export default {
  components: {
    EditorTxt,
    emailReviewView
  },
  props: {
    // 操作按钮状态
    showBtnStatus: {
      type: Boolean,
      default: () => true
    },
    // 流程中的状态
    otherBtnHide: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      // 表单参数
      form: {},
      // 遮罩层
      loading: true,
      // 表单校验
      rules: {
        fundId: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        period: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        fundScale: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        callProp: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        callMoney: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        subscribedAmount: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        title: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        context: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
      },
      // 关键字
      keywordList: [],
      lpTemplate: [],
      // 字段隐藏
      displayNone: {
        // 分配批次
        period: false,
        // 基金规模
        fundScale: false,
        // Call款比例
        callProp: false,
        // Call款金额
        callMoney: false,
        // 认缴金额
        subscribedAmount: false
      },
      // 上传
      uploadStyle: 'color: #fff;background-color: #1890ff;border-color: #1890ff;padding: 7px 15px;font-size: 12px;border-radius: 3px;',
      uploadLoading: false,
      allocationPeriodDict: [],
      // 出资人
      lpInvestorOpen: false,
      title: '',
      LpBulletinInvestorLoading: false,
      emailReviewViewOpen: false,
      thisPageData: undefined,
      lpEmailVisible: [],
      lpEmailCcVisible: [],
      fileFormatArr: {}
    }
  },
  created() {
    // 获取公告类型
    listLpAnnouncementTemplate().then(response => {
      this.lpTemplate = response.rows
    })
    this.getDicts('lp_poster_keywords').then(response => {
      this.keywordList = response.data
    })
  },
  methods: {
    // 初始化数据 listOfFundersInTheFund
    init(data) {
      if (data !== null && data.id !== undefined) {
        this.thisPageData = data
        this.loading = true
        getLpPublicBulletin(data.id).then(response => {
          this.form = response.data
          this.loading = false
        })
      } else {
        this.reset()
      }
    },
    // 取消按钮
    cancel() {
      if (this.$parent.$parent.formOpen === true) {
        this.$parent.$parent.formOpen = false
        this.$parent.$parent.reset()
        this.$parent.$parent.getList()
      }
      this.$parent.$parent.emailReviewOpen = false
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      this.$parent.$parent.formOpen = false
      // 刷新list页面
      this.$parent.$parent.getList()
      if (this.$parent.$parent.emailReviewOpen !== undefined) {
        this.$parent.$parent.emailReviewOpen = false
      }
    },
    // 校验邮箱
    checkInvestEmail(value) {
      var flag = true
      if (!this.isEmpty(value)) {
        const email = value.split(';')
        if (email.length > 0) {
          email.forEach((v) => {
            var ofi = v.indexOf('@')
            if (ofi !== -1) {
              var start = v.substring(0, ofi)
              var end = v.substring(ofi + 1)
              var startNum = start.length
              var endNum = end.length
              if (startNum <= 0 || endNum <= 0) {
                flag = false
                this.msgError(this.$t('请输入有效的邮箱'))
              }
              if (this.countChar(v, '@') !== 1) {
                flag = false
                this.msgError(this.$t('请输入有效的邮箱'))
              }
            } else {
              flag = false
              this.msgError(this.$t('请输入有效的邮箱'))
            }
          })
        }
      }
      return flag
    },
    /**
     * 工具: 获取字符串中有几个指定字符
     */
    countChar(str, char) {
      let count = 0
      for (let i = 0; i < str.length; i++) {
        if (str[i] === char) {
          count++
        }
      }
      return count
    },
    querySearch(queryString, index, type, lpId) {
      if (this.isEmpty(queryString)) {
        listDealContacts({ businessId: this.form.lpBaseList[index].lpId }).then(response => {
          var restaurants = []
          response.rows && response.rows.forEach(item => {
            if (!this.isEmpty(item.email)) {
              restaurants.push({ email: '(' + item.contactsName + ')' + item.email, value: '(' + item.contactsName + ')' + item.email })
            }
          })
          this.$set(this.fileFormatArr, lpId, restaurants)
          this.$forceUpdate()
        })
      } else {
        if (type === 'lpEmail') {
          this.$set(this.form.lpBaseList[index], 'emailValue', queryString)
        }
        if (type === 'lpEmailCc') {
          this.$set(this.form.lpBaseList[index], 'emailCcValue', queryString)
        }
      }
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.email.indexOf(queryString) === 0)
      }
    },
    closeAllInput() {
      if (this.lpEmailVisible) {
        Object.keys(this.lpEmailVisible).forEach(item => {
          this.lpEmailVisible[item] = false
        })
      }
      if (this.lpEmailCcVisible) {
        Object.keys(this.lpEmailCcVisible).forEach(item => {
          this.lpEmailCcVisible[item] = false
        })
      }
    },
    // 格式化邮箱显示
    splitEmail(row, field) {
      if (this.isEmpty(row[field])) {
        row[field] = ''
        return ''
      }
      return row[field].split(';')
    },
    handleClose(row, index, tag, type) {
      if (type === 'to') {
        var lpEmail = row.lpEmail.split(';')
        lpEmail.splice(lpEmail.indexOf(tag), 1)
        if (lpEmail.length === 0) {
          this.$set(this.form.lpBaseList[index], 'lpEmail', undefined)
        } else {
          this.$set(this.form.lpBaseList[index], 'lpEmail', lpEmail.join(';'))
        }
      }
      if (type === 'cc') {
        var lpEmailCc = row.lpEmailCc.split(';')
        lpEmailCc.splice(lpEmailCc.indexOf(tag), 1)
        this.form.lpBaseList[index].lpEmailCc = lpEmailCc.join(';')
      }
      this.$forceUpdate()
    },
    handleEmailConfirm(row, val) {
      if (val.target.value) {
        row.emailValue = val.target.value
      }
      setTimeout(() => {
        if (this.checkInvestEmail(row.emailValue)) {
          if (row.emailValue) {
            var lpEmailTemp = row.lpEmail.split(';')
            lpEmailTemp.push(row.emailValue)
            lpEmailTemp = lpEmailTemp.filter((item) => !!item)
            row.lpEmail = lpEmailTemp.join(';')
          }
        }
        this.lpEmailVisible[row.lpId] = false
        row.emailValue = ''
      }, 100)
    },
    handleEmailCcConfirm(row, val) {
      if (val.target.value) {
        row.emailCcValue = val.target.value
      }
      setTimeout(() => {
        if (this.checkInvestEmail(row.emailCcValue)) {
          if (row.emailCcValue) {
            var lpEmailTemp = row.lpEmailCc.split(';')
            lpEmailTemp.push(row.emailCcValue)
            lpEmailTemp = lpEmailTemp.filter((item) => !!item)
            row.lpEmailCc = lpEmailTemp.join(';')
          }
        }
        this.lpEmailCcVisible[row.lpId] = false
        row.emailCcValue = ''
      }, 100)
    },
    showEmailInput(row) {
      this.closeAllInput()
      this.$set(this.form.lpBaseList, 'emailValue', '')
      this.$set(this.lpEmailVisible, row.lpId, true)
    },
    showEmailCcInput(row) {
      this.closeAllInput()
      this.$set(this.form.lpBaseList, 'emailCcValue', '')
      this.$set(this.lpEmailCcVisible, row.lpId, true)
    },
    // 预览附件
    onlinePreview(id) {
      this.$refs.OnlinePreview.onlinePreviewFile(id)
    },
    // 驳回
    turnDown() {
      this.loading = true
      updateReviewStatus(this.form.id, '已驳回').then(response => {
        this.msgInfo(this.$t(response.msg))
        this.closeForm()
      })
    },
    // 查看发送公告给出资人详细内容
    emailReviewView(row) {
      this.title = this.$t('出资人公告内容')
      this.emailReviewViewOpen = true
      this.$nextTick(() => {
        this.$refs.emailReviewView.init({ id: row.parentId, lpId: row.lpId })
      })
    },
    // 发送邮件复核
    submitForm: function() {
      this.loading = true
      resendReviewAnnouncement(this.form).then(mainRes => {
        if (mainRes.data === 'success') {
          this.init(this.thisPageData)
        } else {
          this.loading = false
          this.msgError(this.$t(mainRes.data))
        }
      })
    },
    // 发送失败, 维护邮箱
    submitEmail(row) {
      var _this = this
      this.$confirm(this.$t('确定需要重新发送?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        _this.loading = true
        var mailboxMaintenanceForm = JSON.parse(JSON.stringify(_this.form))
        var rowTemps = JSON.parse(JSON.stringify(row))
        _this.$set(rowTemps, 'lpEmail', rowTemps.lpEmail)
        _this.$set(rowTemps, 'lpEmailCc', rowTemps.lpEmailCc)
        mailboxMaintenanceForm.lpBaseList = [rowTemps]
        resendReviewAnnouncement(mailboxMaintenanceForm).then(() => {
          // 重新加载页面
          _this.init(_this.thisPageData)
        })
      }).catch(() => {
      })
    }
  }
}

</script>
<style scoped lang="scss">
/deep/.tox-editor-header {
  display: none;
}
</style>
